package tech.yixiyun.framework.kuafu.db.sql.handler;

import tech.yixiyun.framework.kuafu.domain.BaseDomain;
import org.apache.commons.dbutils.ResultSetHandler;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 插入数据后，如果有自增列，根据Field对自增结果做处理
 */
public class IdsColumnHandler implements ResultSetHandler {
    private Field idField; //id字段
    private List<BaseDomain> instances;
    public IdsColumnHandler(Field idField, List<BaseDomain> instances) {
        this.idField = idField;
        this.instances = instances;
    }
    @Override
    public Object handle(ResultSet rs) throws SQLException {
        if (idField == null || rs.next() == false) return null;
        Object v = null;
        try {
            if (idField.getType().equals(Integer.TYPE) || idField.getType().equals(Integer.class)) {
                for (BaseDomain instance : instances) {
                    idField.set(instance, rs.getInt(1));
                    rs.next();
                }
            } else if (idField.getType().equals(Long.TYPE) || idField.getType().equals(Long.class)) {
                for (BaseDomain instance : instances) {
                    idField.set(instance, rs.getLong(1));
                    rs.next();
                }
            }
           
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
